package tresp.utils.team;

import java.util.concurrent.atomic.AtomicReference;

import robocode.ScannedRobotEvent;
import tresp.bthreads.BThread;
import tresp.bthreads.BThreadType;
import tresp.coordinator.ICoordinator;
import tresp.utils.BThreadVote;
import tresp.utils.ITankInfo;


/**
 * <b>AvoidTeamMatesCollision</b>
 * 
 * 
 * @author <font color="blue">Maxim Kirilov</font>
 *
 */
public class AvoidTeamMatesCollision extends BThread {

    private ITankInfo tankInfo;
    
    private AtomicReference<ScannedRobotEvent>  lastScannedRobotEvent;
    
    public AvoidTeamMatesCollision(ICoordinator<BThreadVote> coordinator) {
	super(coordinator);
	weight = 50D;
	lastScannedRobotEvent = new AtomicReference<ScannedRobotEvent>();
	tankInfo = coordinator.getTankInfo();
    }

    @Override
    public void vote() {
	ScannedRobotEvent e = lastScannedRobotEvent.getAndSet( null );
	
	if ( e != null && tankInfo.isTeammate( e.getName() )){
	    
	    if (Math.abs( tankInfo.getHeading() + e.getHeading() ) < 5){
		coordinator.vote(createBThreadVote(BThreadType.TURN_LEFT_DEGREES, weight, 90D));
	    }
	    
	}

    }

    @Override
    public String getName() {

	return "AvoidTeamMatesCollision";
    }
    
    
    @Override
    public void onScannedRobot(ScannedRobotEvent event){
	lastScannedRobotEvent.set(event);
    }

}
